package cn.wangzg.courseanimation;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class FrameActivity extends AppCompatActivity {
    private ImageView mIvFrame;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frame);

        mIvFrame = findViewById(R.id.imageView);
        //AnimationDrawable animationDrawable = (AnimationDrawable) mIvFrame.getBackground();
        //animationDrawable.start();
    }

    public void runFrame(View view) {
        //完全编码实现的动画效果
        AnimationDrawable anim = new AnimationDrawable();
        for (int i = 1; i <= 4; i++) {
            //根据资源名称和目录获取R.java中对应的资源ID
            int id = getResources().getIdentifier("progress_" + i, "drawable", getPackageName());
            //根据资源ID获取到Drawable对象
            Drawable drawable = getResources().getDrawable(id);
            //将此帧添加到AnimationDrawable中
            anim.addFrame(drawable, 100);

        }
        anim.setOneShot(false); //设置为loop
        mIvFrame.setBackground(anim); //将动画设置为ImageView背景
        anim.start();  //开始动画
    }

    public void btnBigPic(View view){
        AnimationDrawable anim = new AnimationDrawable();
        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.dh);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int pieceWidth = width / 4;
        int pieceHeight = height / 2;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 4; j++) {
                int xValue = j * pieceWidth;
                int yValue = i * pieceHeight;
                Bitmap bm = Bitmap.createBitmap(bitmap, xValue, yValue,
                        pieceWidth, pieceHeight);
                Drawable drawable = new BitmapDrawable(getResources(),bm);
                //将此帧添加到AnimationDrawable中
                anim.addFrame(drawable, 100);
            }
        }
        anim.setOneShot(false); //设置为loop
        mIvFrame.setBackground(anim); //将动画设置为ImageView背景
        anim.start();  //开始动画
    }
}
